package com.elink.enginerring.file.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.elink.enginerring.common.BaseCo;
import com.elink.enginerring.common.Constant;
import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.common.Pagination;
import com.elink.enginerring.file.co.FileCo;
import com.elink.enginerring.file.dao.BuildFileMapper;
import com.elink.enginerring.file.dao.CertFileMapper;
import com.elink.enginerring.file.dao.FileCacheMapper;
import com.elink.enginerring.file.dao.FileMapper;
import com.elink.enginerring.file.dao.TagMapper;
import com.elink.enginerring.file.entity.BuildFile;
import com.elink.enginerring.file.entity.File;
import com.elink.enginerring.file.entity.FileCache;
import com.elink.enginerring.fileDc.dao.FileDcMapper;
import com.elink.enginerring.fileDc.entity.FileDc;
import com.elink.enginerring.util.DCSTest;
import com.elink.enginerring.util.IDGenerator;
import com.elink.enginerring.util.JSONUtil;
import com.elink.enginerring.video.dao.HierFileMapper;
import com.elink.enginerring.video.dao.SkillFileMapper;
import com.elink.enginerring.video.dao.SkillMapper;
import com.elink.enginerring.video.entity.HierFile;
import com.elink.enginerring.video.entity.Skill;
import com.elink.enginerring.video.entity.SkillFile;

@Service
public class FileService implements IFileService {
	@Autowired
	private FileMapper fileMapper;
	@Autowired
	private FileDcMapper fileDcMapper;
	@Autowired
	private TagMapper tagMapper;
	@Autowired
	private BuildFileMapper buildFileMapper;
	@Autowired
	private CertFileMapper certFileMapper;
	@Autowired
	private SkillFileMapper skillFileMapper;
	@Autowired
	private SkillMapper  skillMapper;
	@Autowired
	private HierFileMapper hierFileMapper;
	@Autowired
	private FileCacheMapper  fileCacheMapper;
	@Override
	public Map<String, Object> getListOfPage(FileCo co) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", fileMapper.selectList(co));
		map.put("pagination", new Pagination(co, fileMapper.selectCount(co)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> add(File file, String dcIds) {
		String fileId = IDGenerator.gen32UUID();
		file.setFileId(fileId);
		file.setUploadTime(new Date());
		file.setAuthStatus(1);
		fileMapper.insertSelective(file);
		
		List<FileDc> fdc = new ArrayList<FileDc>();
		if(dcIds != null && dcIds != ""){
			for (String dcId : dcIds.split(",")) {
				FileDc f = new FileDc();
				f.setDcId(Integer.parseInt(dcId));
				f.setFileId(fileId);
				fdc.add(f);
			}
			fileDcMapper.insertBatch(fdc);
			
			//转码
			final String fileid = fileId;
			final File f = file;
			new Thread() {  
			    public void run() {  
			    	 wordToPng( fileid,f.getPath(),  f.getUserId(), f.getTypeId());
			    };  
			}.start();
		}
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,fileId);
	}

	@Override
	public Map<String, Object> del(String ids) {
		fileMapper.del(ids);
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public File getInfo(String fileId) {
		return fileMapper.selectInfo(fileId);
	}

	@Override
	public Map<String, Object> modify(File file, String dcIds) {
		
		//1,删除旧的dcId
		fileDcMapper.del(file.getFileId());
		
		
		//2.转码
		File oldFile = fileMapper.selectByFilePath(file.getPath());
		if(oldFile ==null){
			//删掉转码的文件
			fileCacheMapper.deleteByFileId(file.getFileId());
			//重新转码
			//转码
			final String fileid = file.getFileId();
			final File f = file;
			new Thread() {  
			    public void run() {  
			    	 wordToPng( fileid,f.getPath(),  f.getUserId(), f.getTypeId());
			    };  
			}.start();
		}
		
		//3,更新文件
		fileMapper.updateByPrimaryKeySelective(file);
		//4,插入新的dcid
		List<FileDc> fdc = new ArrayList<FileDc>();
		if(dcIds != null && dcIds != ""){
			for (String dcId : dcIds.split(",")) {
				FileDc fd = new FileDc();
				fd.setDcId(Integer.parseInt(dcId));
				fd.setFileId(file.getFileId());
				fdc.add(fd);
			}
			fileDcMapper.insertBatch(fdc);
		}
		
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}
	

	@Override
	public Map<String, Object> addBuildFile(BuildFile file, String dcIds) {
		Date date = new Date();
		List<BuildFile> fdc = new ArrayList<BuildFile>();
		if(dcIds != null && dcIds != ""){
			for (String dcId : dcIds.split(",")) {
				BuildFile f = new BuildFile();
				f.setFileId(dcId);
				f.setTcId(file.getTcId());
				f.setScId(file.getScId());
				f.setDcId(file.getDcId());
				f.setHierId(file.getHierId());
				f.setGrade(file.getGrade());
				f.setOperationUserId(file.getOperationUserId());
				f.setOperationTime(date);
				fdc.add(f);
			}
			buildFileMapper.insertBatch(fdc);
		}
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}

	@Override
	public Map<String, Object> addCertFile(BuildFile file, String dcIds) {
		Date date = new Date();
		List<BuildFile> fdc = new ArrayList<BuildFile>();
		if(dcIds != null && dcIds != ""){
			for (String dcId : dcIds.split(",")) {
				BuildFile f = new BuildFile();
				f.setFileId(dcId);
				f.setTcId(file.getTcId());
				f.setScId(file.getScId());
				f.setDcId(file.getDcId());
				f.setHierId(file.getHierId());
				f.setGrade(file.getGrade());
				f.setOperationUserId(file.getOperationUserId());
				f.setOperationTime(date);
				fdc.add(f);
			}
			certFileMapper.insertBatch(fdc);
		}
		return JSONUtil.getJSON(ErrorType.SUCCESS);
	}
	
	@Override
	public Map<String, Object> addSkillFile(int skillId, String fileIds) {
		List<SkillFile> fdc = new ArrayList<SkillFile>();
		if(fileIds != null && fileIds != ""){
			String[] fileIdList =  fileIds.split(",");
			for (String dcId : fileIdList) {
				SkillFile f = new SkillFile();
				f.setFileId(dcId);
				f.setSkillId(skillId);
				fdc.add(f);
			}
			skillFileMapper.insertBatch(fdc);
			//更新skill的资料数
			Skill skill = skillMapper.selectByPrimaryKey(skillId);
			skill.setDataCount(skill.getDataCount()+fileIdList.length);
			skillMapper.updateByPrimaryKeySelective(skill);
		}
			return JSONUtil.getJSON(ErrorType.SUCCESS);
	}
	
	@Override
	public Map<String, Object> addPlanFile(HierFile file, String fileIds) {
		List<HierFile> fdc = new ArrayList<HierFile>();
		if(fileIds != null && fileIds != ""){
			String[] fileIdList =  fileIds.split(",");
			for (String dcId : fileIdList) {
				HierFile f = new HierFile();
				f.setFileId(dcId);
				f.setHierId(file.getHierId());
				f.setGrade(file.getGrade());
				f.setOperationTime(new Date());
				f.setOperationUserId(file.getFileId());
				fdc.add(f);
			}
			hierFileMapper.insertBatch(fdc);
		}
		return JSONUtil.getJSON(ErrorType.SUCCESS); 
	}
	@Override
	public Map<String, Object> getFileListByCondition(BaseCo co, int type,int count,String joinTable,boolean flag,String userId,String fileName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", fileMapper.selectFileListByCondition(co,type,count,joinTable,flag,userId,fileName));
		map.put("pagination", new Pagination(co, fileMapper.selectCountOfFileListByCondition(type,count,joinTable,flag,userId,fileName)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Override
	public Map<String, Object> getCountByCondition(int type, String joinTable) {
		return JSONUtil.getJSON(ErrorType.SUCCESS, fileMapper.selectCountByCondition(type,joinTable));
	}

	@Override
	public Map<String, Object> getSkillFile(BaseCo co, String skillId,String keyWord) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", fileMapper.selectSkillFile(co,skillId,keyWord));
		map.put("pagination", new Pagination(co, fileMapper.selectCountOfSkillFile(skillId,keyWord)));
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}

	@Transactional
	public  Map<String, Object> wordToPng(String fileId,String filePath,String userId,int type){
		int pageCount = 0;
		String convertByUrl = "";
		JSONObject jsStr = null;
		String path = "";
		boolean urlFlag = true;
			FileCache fileCache = new FileCache();
			fileCache.setFileId(fileId);
			int fileType = 10;
			String ext = ".png";
			if ( type == 14 || type== 15) {// 文档
				fileType = 5;
			} else if (type == 16) {// 压缩文件
				fileType = 19;
			}else if (type == 1){ //word文档
				fileType = 6;
				ext = ".jpg";
			}
			do {
				// 网络转换
				convertByUrl = DCSTest.sendPost(
						Constant.OFFICE_SERVER_IP,
						"downloadUrl="+Constant.DOWNLOAD_URL+""+filePath + "&convertType=" + fileType+"&showFooter=1&isDelSrc =1"
								+ "&showFooter=1&isDelSrc =1&destinationName="+filePath.substring(filePath.indexOf(".")-32,filePath.indexOf(".")));
				System.out.println("转换结果"+convertByUrl);
				jsStr = JSONObject.parseObject(convertByUrl);
				System.out.println("转换结果1"+jsStr);
				if (jsStr != null) {
					urlFlag = false;
				}
			} while (urlFlag);

			if (Integer.parseInt(jsStr.getString("result")) == 0) {// 转换成功则插入数据
				String oldPath  = jsStr.getString("data").substring(1,	jsStr.getString("data").length() - 1).replaceAll("\"", "");
				if(fileType == 19){//rar文件
					path = oldPath;
					pageCount = 1;
				}else{
					//路径需要排序
					pageCount = jsStr.getString("data").split(",").length;
					int[] sort =  new int[pageCount];
					for (int i = 0; i < pageCount; i++) {
						sort[i] = Integer.parseInt( oldPath.split(",")[i].substring(oldPath.split(",")[i].lastIndexOf("/")+1,oldPath.split(",")[i].length()-4));;
					}
					Arrays.sort(sort);
					for (int i = 0; i < sort.length; i++) {
						path +=oldPath.split(",")[0].substring(0,oldPath.split(",")[0].lastIndexOf("/")+1) +sort[i]+ext+"#";
					}		
					path = path.substring(0,path.length()-1);
				}
				fileCache.setPreviewPath(path);
				fileCache.setPageCount(pageCount);
				fileCache.setType(1);
				fileCacheMapper.insertSelective(fileCache);
				return JSONUtil.getJSON(ErrorType.SUCCESS);
			}
			if (Integer.parseInt(jsStr.getString("result")) == 18) {// 文件下载失败
				return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
			}
		return JSONUtil.getJSON(ErrorType.FILE_DOWNLOAD_ERROR);
	}
}
